<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/06/02
// +----------------------------------------------------------------------

namespace app\user_center\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 手动充值
 * @package app\cms\admin
 */
class MaualRecharge extends Admin
{
    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return mixed
     */
    public function manual_recharge_list()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();

        //tab
        $list_tab = [
            'tab1' => ['title' => '待充值', 'url' => url('manual_recharge_list', ['group' => 'tab1'])],
            'tab2' => ['title' => '已充值', 'url' => url('manual_recharge_list', ['group' => 'tab2'])],
        ];

        // 数据列表[进行中/结束/禁用/全部/]
        $group = isset($data['group']) ? $data['group'] : 'tab1';
        switch ($group) {
            case 'tab1':
                $map[] = ['status','=',0];
                break;
            case 'tab2':
                $map[] = ['status','=',1];
                break;
            default:
                break;
        }
        //数据列表
        $data_list =  model('UcMemberManualRecharge', 'model\user')->where($map) -> order('id desc') -> paginate();//获取列表
        // 使用ZBuilder快速创建数据表格
        if($group == 'tab1'){
            return ZBuilder::make('table')
                ->setPageTitle('待充值账号') // 设置页面标题
                ->hideCheckbox()
                ->setPrimaryKey('id') // 设置主键名为id
                ->setTableName('uc_member_manual_recharge') // 设置数据表名
                ->addColumns([ // 批量添加列
                    // ['__INDEX__', '序号'],
                    ['id', 'Id'],
                    ['tel', '手机号', 'text'],
                    ['price', '价值', 'text'],
                ])
                ->setSearchArea([
                    ['text', 'tel', '手机号', 'like'],
                ])
                ->setTabNav($list_tab,  $group)
                ->addTopButton('custom', ['title' => '批量充值', 'href' => url('user_center/maual_recharge/manual_recharge_all')])
                ->setRowList($data_list) // 设置表格数据
                ->fetch(); // 渲染页面
        }else{
            return ZBuilder::make('table')
                ->setPageTitle('待充值账号') // 设置页面标题
                ->hideCheckbox()
                ->setPrimaryKey('id') // 设置主键名为id
                ->setTableName('uc_member_manual_recharge') // 设置数据表名
                ->addColumns([ // 批量添加列
                    ['id', 'Id'],
                    ['tel', '手机号', 'text'],
                    ['price', '价值', 'text'],
                    ['update_time', '充值时间', 'datetime'],
                ])
                ->setSearchArea([
                    ['text', 'tel', '手机号', 'like'],
                ])
                ->setTabNav($list_tab,  $group)
                ->setRowList($data_list) // 设置表格数据
                ->fetch(); // 渲染页面
        }

    }

    public function manual_recharge_all($id=[])
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        //获取筛选
        $map = $this->getMap();
        //数据获取
        $data = input();
        $map[] = ['status','=',0];
        if(!empty($id)){
            $map[] = ['id','in',$id];
        }
        //数据列表
        $data_list =  model('UcMemberManualRecharge', 'model\user')->where($map) -> order('id desc') -> column('*');//获取列表

        //查找会员表比对tel,存在则添加价格，不存在则注册用户
        if(!empty($data_list)){
            foreach ($data_list as $key=>$value){
                $is_have = model('UcMemberMobile','model\user')->where('mobile','=',$value['tel'])->find();
                if(!empty($is_have)){
                    //直接更新对应余额
/*                    $data = [
                        'balance' => Db::raw('balance+'.$value['price']),
                        ];
                    $res = model('Member', 'model\user')->where('uid',$is_have['uid'])->update($data);*/
                    $res = 1;
                    $uid = $is_have['uid'];
                }else{
                    //注册
                    $res =  controller('user_center/Userlogic',"logic\user") -> login_mobile_balance($value['tel'], 1234, 0);
                    $uid = $res['data']['userId'];
                }
                if($res){
                    //更新表status=1(已操作)
                    $rel = model('UcMemberManualRecharge', 'model\user')->editData($value['id']);
                    if($rel){
                        //写入储值流水表中
                        $code_count = model('UcMemberBalance', 'model\user')->where('pay_type','=',0) ->count();
                        $order_code = 'BMR'.date('Ymd').(str_pad(($code_count+1),3,"0",STR_PAD_LEFT));
                        $pay_order_id = '0000000000';
                        $in_balance = model('UcMemberBalance', 'model\user')->addDataBmr($uid, $order_code,$pay_order_id, $value['price'], 0, 2);
                        if($in_balance){
                            $price = $value['price'];
                            $use_rule = 0;
                            $log_remark = '管理员通过订单['.$order_code.']手动充值'.$price;
                            $in_balance_log = model('UcMemberBalanceJournalLog', 'model\user')->addData($uid, $in_balance['data'], 1, $price, $use_rule, $log_remark);
                        }
                    }
                }
            }
            $this->success('充值成功');
        }else{
           $this->success('没有待充值账号请刷新重试或联系管理员');
        }
    }


}